<?php

namespace app\common\model\Teacher;

use think\Model;
use think\Request;

//引入模型
use app\common\model\Subject\Subject; 
use app\common\model\Teacher\Follow;

class Teacher extends Model
{
    //指定模型可操作的表名
    protected $name = "teacher";

    //也可以写$table,但此时要加表前缀 
    //protected $table ="fa_subject_teacher"

    //指定自动插入时间戳
    protected $autoWriteTimestamp = true;

    //指定插入时间戳的字段
    protected $createTime = "createtime";

    //更新时间戳时不进行写入操作
    protected $updateTime = false;

    //忽略数据表中不存在的字段
    protected $field = true;
    
    //追加虚拟字段
    protected $append = [
        'follows_text',
        'avatar_text',
        'count_text'
    ];

    //课程总数的虚拟字段
    public function getCountTextAttr($value,$data)
    {
        $id = isset($data['id']) ? trim($data['id']): 0 ;

        $SubjectModel = new Subject();

        $count = $SubjectModel->where(['teacherid' => $id])->count();

        return $count;
    }
    //头像的虚拟字段
    public function getAvatarTextAttr($value,$data)
    {
        //先获取到图片信息
        $avatar = isset($data['avatar']) ? trim($data['avatar']): '';

        //若图片为空或图片不存在
        //则为这两种情况展示系统自带默认图
        if(empty($avatar)|| !is_file(".".$avatar))
        {
            $avatar = "/assets/img/cover.png";
        }

        //组装完整地址
        // http://www.fast.com/assets/img/cover.png

        //获取当前域名
        $request = Request :: instance(); 
        $domain = $request -> domain();

        //拼接 用'.'进行拼接
        $avatar = $domain.$avatar; 
        return $avatar;
    }
    //关注的粉丝数
    public function getFollowsTextAttr($value,$data)    
    {
        $teacherid = isset($data['id']) ? trim($data['id']) : 0;

        return Follow :: where(['teacherid' => $teacherid])->count();
    }
}
